<?php
namespace app\admin\service;

use app\common\model\MachineModel;
use app\common\model\OperateModel;
use app\common\model\UserModel;
use app\common\model\ProtectModel;
use think\Session;

class AdminService
{
    private static $model;
    private static $operateModel;
    private static $machineModel;
    private static $protectModel;

    public function __construct(UserModel $userModel, OperateModel $operateModel, MachineModel $machineModel, ProtectModel $protectModel)
    {
        self::$model = $userModel;
        self::$operateModel = $operateModel;
        self::$machineModel = $machineModel;
        self::$protectModel = $protectModel;
    }

    /**
     * 创建后台管理员
     * User: zhouyao
     * Date: 2018/12/1
     * Time: 2:12 PM
     * @param $params
     * @return  mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function create($params)
    {
        if (empty($params) || !isset($params['account_name']) || !isset($params['password']) || !isset($params['type'])) {
            return app_fail(9983);
        }
        // 查看用户是否存在
        $ext = self::$model->where(['account_name' => $params['account_name'], 'phone' => $params['phone']])->find();
        if (!empty($ext)) {
            return app_fail(9995);
        }
        $params['password'] = md5($params['password']);
        $params['create_time'] = $params['update_time'] = time();
        try {
            $row = self::$model->allowField(true)->save($params);
            return $row;
        } catch (\Exception $e) {
            return app_fail(9998);
        }
    }

    /**
     * 显示管理员列表
     * User: zhouyao
     * Date: 2018/12/1
     * Time: 2:21 PM
     * @param $param
     * @return array
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists($param)
    {
        if (empty($param) || !isset($param['page']) || !isset($param['limit'])) {
            app_fail(9997); // 参数异常
        }
        $where = [
            ['type', '<', 3]
        ];
        if (!empty($param['type']) && $param['type'] == 3) {
            $where = ['type' => 3];
        }
        
        // 获取总数
        $count = self::$model->where($where)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => (int) $count];
        }

        // 查询管理员列表
        $result = self::$model->where($where)
            ->page($param['page'])
            ->limit($param['limit'])
            ->order('type', 'asc')
            ->order('id', 'asc')
            ->select();

        $result->each(function ($item) {
           $item->update_time = date('Y-m-d H:i:s', $item->update_time);
           $item->type = intval($item->type);
           return $item;
        });

        return ['data' => $result, 'count' => (int) $count];
    }

    /**
     * 查看指定管理员信息
     * User: zhouyao
     * Date: 2018/12/1
     * Time: 2:29 PM
     * @param $param
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($param)
    {
        if (empty($param) || !isset($param['id'])) {
            app_fail(9997);
        }

        // 查询当前用户是否存在
        $admin = self::$model->where('id', '=', $param['id'])
            ->find();

        return $admin;
    }

    /**
     * 更改管理员基本信息
     * User: zhouyao
     * Date: 2018/12/1
     * Time: 2:31 PM
     * @param $param
     * @return bool
     * @throws \app\common\exception\AppException
     */
    public function update($param)
    {
        if (empty($param) || !isset($param['id'])) {
            app_fail( 9997);
        }
        $data = [];
        // 拼装数据
        if (!empty($param['account_name'])) {
            $data['account_name'] = $param['account_name'];
        }
        if (!empty($param['phone'])) {
            $data['phone'] = $param['phone'];
        }
        if (!empty($param['type'])) {
            $data['type'] = $param['type'];
        }
        if (!empty($param['password'])) {
            $data['password'] = md5($param['password']);
        }
        if (!empty($param['nickname'])) {
            $data['nickname'] = $param['nickname'];
        }
        if (!empty($param['remark'])) {
            $data['remark'] = $param['remark'];
        }

        // 查询用户类型
        $user = self::$model->where(['id' => $param['guid']])->find();
        if ($user['type'] != 1 && $user['id'] != $param['id']) {
            return app_fail(1000);
        }

        try {
            $admin = self::$model->save($data, ['id' => $param['id']]);
            return $admin;
        } catch (\Exception $e) {
            return app_fail(9899);
        }
    }

    /**
     * 更新普通管理员查看测试仪器的权限
     * User: zhouyao
     * Date: 2018/12/1
     * Time: 2:59 PM
     * @param $param
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateRole($param)
    {
        if ($param['code_type'] == 2) {
            return $this->updateProtectCode($param);
        }

        if (empty($param) || !isset($param['user_id'])) {
            return app_fail(9997);
        }
        $param['data'] = $param['machine'];
        
        // 查询已经存在的可查看测试仪器
        $operateList = self::$operateModel->where([
                ['machine_code', '<>', ''],
                ['user_id', '=', $param['user_id']]
            ])->field('machine_code')
            ->select();
        $oldMachine = $operateList->column('machine_code');
        $data = [];
        foreach ($param['data'] as $key => $val) {
            // if (!in_array($val, $oldMachine)) {
                $data[] = [
                    'machine_code' => $val,
                    'user_id' => $param['user_id'],
                    'create_time' => time(),
                    'update_time' => time()
                ];
            // }
        }

        try {
            self::$operateModel->where('user_id', '=', $param['user_id'])->where('machine_code', '<>', '')->delete();
            self::$operateModel->saveAll($data);
            return true;
        } catch (\Exception $e) {
            return app_fail(9899);
        }
    }

    /**
     * 编辑指定查看的保护列表
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    private function updateProtectCode($param)
    {
        if (empty($param) || !isset($param['user_id'])) {
            return app_fail(9997);
        }
        $param['data'] = $param['machine'];
        
        // 查询已经存在的可查看测试仪器
        $operateList = self::$operateModel->where([
                ['res_code', '<>', ''],
                ['user_id', '=', $param['user_id']]
            ])->field('res_code')
            ->select();
        $oldMachine = $operateList->column('res_code');
        $data = [];
        foreach ($param['data'] as $key => $val) {
                $data[] = [
                    'res_code' => $val,
                    'user_id' => $param['user_id'],
                    'create_time' => time(),
                    'update_time' => time()
                ];
        }

        try {
            self::$operateModel->where('user_id', '=', $param['user_id'])->where('res_code', '<>', '')->delete();
            self::$operateModel->saveAll($data);
            return true;
        } catch (\Exception $e) {
            return app_fail(9899);
        }
    }

    /**
     * 显示所有的测试仪器
     * User: zhouyao
     * Date: 2018/12/1
     * Time: 5:14 PM
     * @param $param
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function showMachine($param)
    { 
        // 求出可查看的测试仪器
        $operateList = self::$operateModel->where([
                ['machine_code', '<>', ''],
                ['user_id', '=', $param['user_id']]
            ])->field('machine_code')
            ->select()->toArray();
        $machineCode = array_column($operateList, 'machine_code');

        $machine = self::$machineModel->select()->toArray();

        foreach ($machine as $key => $val) {
            $machine[$key]['is_show'] = 0;
            if (in_array($val['machine_code'], $machineCode)) {
                $machine[$key]['is_show'] = 1;
            }
        }
        if ($param['type'] == 2) {
            return $this->showProtect($param);
        }

        return $machine;
    }

    /**
     * [显示用户所有的保护]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function showProtect($param)
    {
        // 求出可查看的测试仪器
        $operateList = self::$operateModel->where([
                ['res_code', '<>', ''],
                ['user_id', '=', $param['user_id']]
            ])->field('res_code')
            ->select()->toArray();
        $machineCode = array_column($operateList, 'res_code');
        $machine = self::$protectModel->select()->toArray();

        foreach ($machine as $key => $val) {
            $machine[$key]['machine_name'] = $val['res_name']; 
            $machine[$key]['machine_code'] = $val['res_code']; 
            $machine[$key]['is_show'] = 0;
            if (in_array($val['res_code'], $machineCode)) {
                $machine[$key]['is_show'] = 1;
            }
        }
        return $machine;
    }

    /**
     * 删除管理员
     * User: zhouyao
     * Date: 2018/12/1
     * Time: 5:58 PM
     * @param $param
     * @return mixed
     * @throws \app\common\exception\AppException
     */
    public function delete($param)
    {
        if (empty($param) || !isset($param['id'])) {
            return app_fail(9997);
        }

        try {
            self::$model->where(['id' => $param['id']])->delete();
            return true;
        } catch (\Exception $e) {
            return app_fail(9980);
        }
    }

    /**
     * 后台管理员登录
     * User: zhouyao
     * Date: 2018/12/5
     * Time: 8:52 PM
     * @param $param
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login($param)
    {
        if (empty($param) || !isset($param['username']) || !isset($param['password'])) {
            return app_fail(9997); // 参数异常
        }

        // 查询数据库记录是否存在
        $row = self::$model->where('account_name', '=', $param['username'])->find();
        if (empty($row)) {
            return app_fail(7998); //用户不存在
        }

        if ($row->type > 2) {
            return app_fail(1000); // 没有权限
        }

        //检测密码是否正确
        if ($row->password !== md5($param['password'])) {
            return app_fail(7997);
        }

        // 信息都正确 把用户信息存入 redis
        (new Session())->set('adminUser', $row);

        $data = [
            'token' => md5(time()),            //token
            'guid' => $row->id,               // 员工guid，或者渠道guid
            'token_time' => time() + 2592000, // token过期时间
            'code' => 001,

        ];

        $row->save(['update_time' => time()]);

        return $data;
    }

    /**
     * 获取用户权限
     * User: zhouyao
     * Date: 2018/12/5
     * Time: 8:59 PM
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInfo($param)
    {
        $info = self::$model->where('id', '=', $param['guid'])->find();
        $role = [(int)$info->type];
        $username = $info->account_name;
        $data = [
            'last_time' => $info->update_time,   // 最后登录时间
            'username' => $username,    // 用户名
            'role' => $role             // 角色
        ];

        return $data;
    }

    public function total()
    {
        // 获取所有变电站
        $station = db('station')->count();
        // 获取会员总数
        $user = db('user')->where('type', '=', 3)->count();
        // 获取保护总数
        $protect = db('protect_obj')->count();
        //  仪器总数
        $machine = db('machine')->count();
        // 工单总数
        $order = db('order')->count();
        // 报告总数
        $report = db('report')->count();

        return [
            'station' => $station,
            'protect' => $protect,
            'user' => $user,
            'machine' => $machine,
            'order' => $order,
            'report' => $report,

        ];

    }
}